package com.ruoyi.monitor.service.impl;

import java.util.*;

import com.ruoyi.base.domain.BussinessItemVo;
import com.ruoyi.base.service.PublicToolsService;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.monitor.domain.BusWaterIntegrationevaluatedata;
import com.ruoyi.monitor.mapper.BusWaterIntegrationmonitordataYearMapper;
import com.ruoyi.system.service.ISysDictDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.monitor.mapper.BusWaterIntegrationevaluatedataYearMapper;
import com.ruoyi.monitor.domain.BusWaterIntegrationevaluatedataYear;
import com.ruoyi.monitor.service.IBusWaterIntegrationevaluatedataYearService;
import org.springframework.util.CollectionUtils;

/**
 * 手工评价（年）Service业务层处理
 * 
 * @author maliang
 * @date 2025-08-16
 */
@Service
public class BusWaterIntegrationevaluatedataYearServiceImpl implements IBusWaterIntegrationevaluatedataYearService 
{
    @Autowired
    private BusWaterIntegrationevaluatedataYearMapper busWaterIntegrationevaluatedataYearMapper;
    @Autowired
    private ISysDictDataService sysDictDataService;
    @Autowired
    private PublicToolsService publicToolsService;
    @Autowired
    private BusWaterIntegrationmonitordataYearMapper busWaterIntegrationmonitordataYearMapper;

    /**
     * 查询手工评价（年）
     * 
     * @param reportid 手工评价（年）主键
     * @return 手工评价（年）
     */
    @Override
    public BusWaterIntegrationevaluatedataYear selectBusWaterIntegrationevaluatedataYearByReportid(String reportid)
    {
        return busWaterIntegrationevaluatedataYearMapper.selectBusWaterIntegrationevaluatedataYearByReportid(reportid);
    }

    /**
     * 查询手工评价（年）列表
     * 
     * @param busWaterIntegrationevaluatedataYear 手工评价（年）
     * @return 手工评价（年）
     */
    @Override
    public List<BusWaterIntegrationevaluatedataYear> selectBusWaterIntegrationevaluatedataYearList(BusWaterIntegrationevaluatedataYear busWaterIntegrationevaluatedataYear)
    {
        return busWaterIntegrationevaluatedataYearMapper.selectBusWaterIntegrationevaluatedataYearList(busWaterIntegrationevaluatedataYear);
    }

    /**
     * 新增手工评价（年）
     * 
     * @param busWaterIntegrationevaluatedataYear 手工评价（年）
     * @return 结果
     */
    @Override
    public int insertBusWaterIntegrationevaluatedataYear(BusWaterIntegrationevaluatedataYear busWaterIntegrationevaluatedataYear)
    {
        return busWaterIntegrationevaluatedataYearMapper.insertBusWaterIntegrationevaluatedataYear(busWaterIntegrationevaluatedataYear);
    }

    /**
     * 修改手工评价（年）
     * 
     * @param busWaterIntegrationevaluatedataYear 手工评价（年）
     * @return 结果
     */
    @Override
    public int updateBusWaterIntegrationevaluatedataYear(BusWaterIntegrationevaluatedataYear busWaterIntegrationevaluatedataYear)
    {
        return busWaterIntegrationevaluatedataYearMapper.updateBusWaterIntegrationevaluatedataYear(busWaterIntegrationevaluatedataYear);
    }

    /**
     * 批量删除手工评价（年）
     * 
     * @param reportids 需要删除的手工评价（年）主键
     * @return 结果
     */
    @Override
    public int deleteBusWaterIntegrationevaluatedataYearByReportids(String[] reportids)
    {
        return busWaterIntegrationevaluatedataYearMapper.deleteBusWaterIntegrationevaluatedataYearByReportids(reportids);
    }

    /**
     * 删除手工评价（年）信息
     * 
     * @param reportid 手工评价（年）主键
     * @return 结果
     */
    @Override
    public int deleteBusWaterIntegrationevaluatedataYearByReportid(String reportid)
    {
        return busWaterIntegrationevaluatedataYearMapper.deleteBusWaterIntegrationevaluatedataYearByReportid(reportid);
    }

    @Override
    public List<Map> qualityLevelStatis(String id, String startTime, String endTime) {
        List<Map> dataMapList = new ArrayList<>();

        SysDictData dictParam = new SysDictData();
        dictParam.setDictType("water_quality_level");
        List<SysDictData> sysDictDataList = sysDictDataService.selectDictDataList(dictParam);
        Date startDate = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss",startTime+"-01-01 00:00:00");
        Date endDate = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss",endTime+"-12-31 23:59:59");
        List<Map> mapList = busWaterIntegrationevaluatedataYearMapper.qualityLevelStatis(id,startDate,endDate);


        for (SysDictData sysDictData : sysDictDataList) {
            Map dataMap = new HashMap<>();
            String value = "0";
            if(!CollectionUtils.isEmpty(mapList)){
                for (Map map : mapList) {
                    String qualityLevelName = StringUtils.getString(map.get("qualityLevelName"));
                    if(qualityLevelName.equals(sysDictData.getDictLabel())){
                        value = StringUtils.getString(map.get("qualityLevelCount"));
                        break;
                    }
                }
            }
            dataMap.put(sysDictData.getDictLabel(),value);
            dataMapList.add(dataMap);
        }

        return dataMapList;
    }

    @Override
    public Map statisItemCount(String id, String startTime, String endTime) {
        Map<String,List<String>> itemDataList = new HashMap();
        BussinessItemVo vo = new BussinessItemVo();
        vo.setBussinessCategoryCode("MSV");
        List<Map<String,Object>> itemList=publicToolsService.bussinessItemData(vo);
        Date startDate = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss",startTime+"-01-01 00:00:00");
        Date endDate = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss",endTime+"-12-31 23:59:59");

        List<Map> statisList = busWaterIntegrationevaluatedataYearMapper.statisItemCount(id,startDate,endDate);

        while(!startDate.after(endDate)){
            String dayTime = DateUtils.parseDateToStr("yyyy",startDate);
            if(itemDataList.containsKey("dateList")){
                List<String> dateList = itemDataList.get("dateList");
                dateList.add(dayTime);
                itemDataList.put("dateList",dateList);
            }else{
                List<String> dateList = new ArrayList<>();
                dateList.add(dayTime);
                itemDataList.put("dateList",dateList);
            }
            for (Map<String, Object> itemMap : itemList) {
                String itemName = StringUtils.getString(itemMap.get("itemName"));
                Map itemDataMap = new HashMap();
                itemDataMap.put("day",dayTime);
                itemDataMap.put("item",itemName);
                int count = 0;
                for (Map statisMap : statisList) {
                    String statisDay = StringUtils.getString(statisMap.get("dataDay"));
                    String statisItem = StringUtils.getString(statisMap.get("itemName"));
                    String dataCount = StringUtils.getString(statisMap.get("dataCount"));
                    if(statisDay.equals(dayTime) && itemName.equals(statisItem)){
                        count = Integer.valueOf(dataCount);
                        break;
                    }
                }
                if(itemDataList.containsKey(itemName)){
                    List<String> dateList = itemDataList.get(itemName);
                    dateList.add(count+"");
                    itemDataList.put(itemName,dateList);
                }else{
                    List<String> dateList = new ArrayList<>();
                    dateList.add(count+"");
                    itemDataList.put(itemName,dateList);
                }
            }
            startDate = DateUtils.addYears(startDate,1);
        }
        return itemDataList;
    }

    @Override
    public Map trendStatis(String id, String startTime, String endTime,String items) {
        List<String> queryItemList = new ArrayList<>();
        if(StringUtils.isNotEmpty(items)){
            queryItemList = Arrays.asList(items.split(","));
        }

        Map<String,List<String>> itemDataList = new HashMap<>();
        BussinessItemVo vo = new BussinessItemVo();
        vo.setBussinessCategoryCode("MSV");
        List<Map<String,Object>> itemList=publicToolsService.bussinessItemData(vo);
        Date startDate = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss",startTime+"-01-01 00:00:00");
        Date endDate = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss",endTime+"-12-31 23:59:59");

        List<Map> statisList = busWaterIntegrationevaluatedataYearMapper.trendStatis(id,startDate,endDate);

        while(!startDate.after(endDate)){
            String dayTime = DateUtils.parseDateToStr("yyyy",startDate);
            if(itemDataList.containsKey("dateList")){
                List<String> dateList = itemDataList.get("dateList");
                dateList.add(dayTime);
                itemDataList.put("dateList",dateList);
            }else{
                List<String> dateList = new ArrayList<>();
                dateList.add(dayTime);
                itemDataList.put("dateList",dateList);
            }
            for (Map<String, Object> itemMap : itemList) {
                String itemName = StringUtils.getString(itemMap.get("itemName"));
                if(!queryItemList.contains(itemName)){
                    continue;
                }
                Map itemDataMap = new HashMap();
                itemDataMap.put("dataTime",dayTime);
                itemDataMap.put("item",itemName);
                String effectiveValue = "0";
                for (Map statisMap : statisList) {
                    String statisDay = StringUtils.getString(statisMap.get("dataDay"));
                    String statisItem = StringUtils.getString(statisMap.get("itemName"));
                    String effective = StringUtils.getString(statisMap.get("effectiveValue"));
                    if(statisDay.equals(dayTime) && itemName.equals(statisItem)){
                        if(StringUtils.isNotEmpty(effective)){
                            effectiveValue = effective;
                        }
                        break;
                    }
                }
                if(itemDataList.containsKey(itemName)){
                    List<String> dataList = itemDataList.get(itemName);
                    dataList.add(effectiveValue);
                    itemDataList.put(itemName,dataList);
                }else{
                    List<String> dataList = new ArrayList<>();
                    dataList.add(effectiveValue);
                    itemDataList.put(itemName,dataList);
                }
            }
            startDate = DateUtils.addYears(startDate,1);
        }
        return itemDataList;
    }

    @Override
    public Map trendQuality(String id, String startTime, String endTime) {
        Map<String,List<String>> itemDataList = new HashMap();

        SysDictData sysDictDataParam = new SysDictData();
        sysDictDataParam.setDictType("water_quality_level");
        List<SysDictData> sysDictDataList = sysDictDataService.selectDictDataList(sysDictDataParam);
        List<String> levelList = new ArrayList<>();
        sysDictDataList.sort(Comparator.comparing(SysDictData::getDictSort).reversed());
        for (SysDictData sysDictData : sysDictDataList) {
            levelList.add(sysDictData.getDictLabel());
        }
        itemDataList.put("levelList",levelList);

        Date startDate = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss",startTime+"-01-01 00:00:00");
        Date endDate = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss",endTime + "-12-31 23:59:59");

        BusWaterIntegrationevaluatedataYear param = new BusWaterIntegrationevaluatedataYear();
        param.setSegmentid(id);
        param.setStartTime(startDate);
        param.setEndTime(endDate);
        List<BusWaterIntegrationevaluatedataYear> statisList = selectBusWaterIntegrationevaluatedataYearList(param);

        while(!startDate.after(endDate)){
            String dayTime = DateUtils.parseDateToStr("yyyy",startDate);
            if(itemDataList.containsKey("dateList")){
                List<String> dateList = itemDataList.get("dateList");
                dateList.add(dayTime);
                itemDataList.put("dateList",dateList);
            }else{
                List<String> dateList = new ArrayList<>();
                dateList.add(dayTime);
                itemDataList.put("dateList",dateList);
            }
            String itemName = "level";

            Map itemDataMap = new HashMap();
            itemDataMap.put("dataTime",dayTime);
            itemDataMap.put("item",itemName);
            String level = "无类别";

            for (BusWaterIntegrationevaluatedataYear statisMap : statisList) {
                String statisDay = DateUtils.parseDateToStr("yyyy",statisMap.getSampledate());
                if(statisDay.equals(dayTime)){
                    if(StringUtils.isNotEmpty(statisMap.getQualitylevelname())){
                        level = statisMap.getQualitylevelname();
                    }
                    break;
                }
            }
            if(itemDataList.containsKey(itemName)){
                List<String> dataList = itemDataList.get(itemName);
                dataList.add(level);
                itemDataList.put(itemName,dataList);
            }else{
                List<String> dataList = new ArrayList<>();
                dataList.add(level);
                itemDataList.put(itemName,dataList);
            }
            startDate = DateUtils.addYears(startDate,1);
        }
        return itemDataList;
    }

    @Override
    public Map excellentThreeInferiorFiveSum(String ids, String startTime, String endTime, String controlLevelCode) {
        Map resMap = new LinkedHashMap();
        Date startDate = null;
        if(StringUtils.isNotEmpty(startTime)){
            startDate = DateUtils.dateTime("yyy-MM-dd",startTime+"-01-01");
        }
        Date endDate = null;
        if(StringUtils.isNotEmpty(endTime)){
            endDate = DateUtils.dateTime("yyy-MM-dd",endTime+"-12-31");
        }
        List<String> idList = new ArrayList<>();
        if(!StringUtils.isEmpty(ids)){
            idList = Arrays.asList(ids.split(","));
        }
        //优三占比
        List<String> controlLevelCodeList = new ArrayList<>();
        if(StringUtils.isNotEmpty(controlLevelCode)){
            controlLevelCodeList.addAll(Arrays.asList(controlLevelCode.split(",")));
        }
        List<Map> excellentThreeList =  busWaterIntegrationmonitordataYearMapper.excellentThree(idList,startDate,endDate,controlLevelCodeList);

        //超标污染物
        List<Map> cbItemList = busWaterIntegrationmonitordataYearMapper.cbItemList(idList,startDate,endDate,controlLevelCodeList);
        List<String> cbItemNameList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(cbItemList)){
            for (Map map : cbItemList) {
                cbItemNameList.add(StringUtils.getString(map.get("itemName")));
            }
        }
        //劣五
        List<Map> inferiorFiveList = busWaterIntegrationmonitordataYearMapper.inferiorFive(idList,startDate,endDate,controlLevelCodeList);

        List<String> dataTimeList = new ArrayList<>();
        List<String> excellentThreeCountList = new ArrayList<>();
        List<String> excellentThreeProporList = new ArrayList<>();
        List<String> inferiorFiveCountList = new ArrayList<>();
        List<String> inferiorFiveProporList = new ArrayList<>();

        while(!startDate.after(endDate)){
            String year = DateUtils.parseDateToStr("yyyy",startDate);
            dataTimeList.add(year);

            float excellentThreeCount = 0f;
            float inferiorFiveCount = 0f;
            if(!CollectionUtils.isEmpty(excellentThreeList)){
                for (Map excellentThreeMap : excellentThreeList) {
                    String dataYear = StringUtils.getString(excellentThreeMap.get("dataMonth"));
                    if(dataYear.equals(year)){
                        excellentThreeCount = Float.valueOf(StringUtils.getString(excellentThreeMap.get("dataCount")));
                        break;
                    }
                }
            }

            if(!CollectionUtils.isEmpty(inferiorFiveList)){
                for (Map inferiorFiveMap : inferiorFiveList) {
                    String dataYear = StringUtils.getString(inferiorFiveMap.get("dataMonth"));
                    if(dataYear.equals(year)){
                        inferiorFiveCount = Float.valueOf(StringUtils.getString(inferiorFiveMap.get("dataCount")));
                        break;
                    }
                }
            }
            float count = excellentThreeCount + inferiorFiveCount;
            if(count == 0){
                excellentThreeCountList.add("0");
                excellentThreeProporList.add("0");
                inferiorFiveCountList.add("0");
                inferiorFiveProporList.add("0");
            }else{
                excellentThreeCountList.add(excellentThreeCount+"");
                excellentThreeProporList.add(String.format("%.2f",(excellentThreeCount/count)));
                inferiorFiveCountList.add(inferiorFiveCount+"");
                inferiorFiveProporList.add(String.format("%.2f",(inferiorFiveCount/count)));
            }
            startDate = DateUtils.addYears(startDate,1);
        }

        List<String> excellentThreeListTop3 = new ArrayList<>();
        if(!CollectionUtils.isEmpty(excellentThreeList)){
            int count =3;
            if(excellentThreeList.size()<3){
                count = excellentThreeList.size();
            }
            for(int i=0;i<count;i++){
                excellentThreeListTop3.add(StringUtils.getString(excellentThreeList.get(i).get("dataMonth")));
            }
        }
        resMap.put("excellentThreeListTop3",excellentThreeListTop3);

        List<String> inferiorFiveListTop3 = new ArrayList<>();
        if(!CollectionUtils.isEmpty(inferiorFiveList)){
            int count = 3;
            if(inferiorFiveList.size()<3){
                count = inferiorFiveList.size();
            }
            for(int i=0;i<count;i++){
                inferiorFiveListTop3.add(StringUtils.getString(inferiorFiveList.get(i).get("dataMonth")));
            }
        }
        resMap.put("inferiorFiveListTop3",inferiorFiveListTop3);

        resMap.put("cbItemList",cbItemNameList);

        resMap.put("dataTimeList",dataTimeList);
        resMap.put("excellentThreeCountList",excellentThreeCountList);
        resMap.put("excellentThreeProporList",excellentThreeProporList);
        resMap.put("inferiorFiveCountList",inferiorFiveCountList);
        resMap.put("inferiorFiveProporList",inferiorFiveProporList);

        return resMap;
    }
}
